package com.governtalk.backend.repository;

import com.governtalk.backend.entity.SearchHistory;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public interface SearchHistoryRepository extends JpaRepository<SearchHistory, Long> {
    
    // 根据用户ID获取搜索历史
    Page<SearchHistory> findByUserIdOrderBySearchTimeDesc(Long userId, Pageable pageable);
    
    // 根据用户ID获取最近的搜索记录
    List<SearchHistory> findTop10ByUserIdOrderBySearchTimeDesc(Long userId);
    
    // 根据用户ID和搜索类型获取搜索历史
    Page<SearchHistory> findByUserIdAndSearchTypeOrderBySearchTimeDesc(
        Long userId, String searchType, Pageable pageable);
    
    // 删除用户的搜索历史
    void deleteByUserId(Long userId);
    
    // 获取热门搜索关键词
    @Query("SELECT sh.keyword, COUNT(sh.keyword) as count FROM SearchHistory sh " +
           "WHERE sh.searchTime >= :startTime " +
           "GROUP BY sh.keyword " +
           "ORDER BY COUNT(sh.keyword) DESC")
    List<Object[]> findPopularKeywords(@Param("startTime") java.time.LocalDateTime startTime, Pageable pageable);
}
